package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;


    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {


        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //布尔查询，组装多个条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字查询
        if (StringUtils.isBlank(dto.getSearchWords())){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            //按照字段分词之后再查询
            boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR));

            ApUser apUser = AppThreadLocalUtil.get();
            if (null != apUser){
                apUserSearchService.insert(dto.getSearchWords(),apUser.getId());
            }

        }

        //时间范围
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //把布尔查询加入条件构建器
        searchRequest.source().query(boolQuery);

        //分页查询
        searchRequest.source().from(0).size(dto.getPageSize());
        //为了方便测试  发布时间倒叙
        searchRequest.source().sort("publishTime", SortOrder.DESC);

        //高亮显示
        searchRequest.source().highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits totalHits = searchResponse.getHits();
        SearchHit[] hits = totalHits.getHits();
        List<Map> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString,Map.class);

            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (null != highlightFields && highlightFields.size() > 0){
                HighlightField highlightField = highlightFields.get("title");
                Text[] texts = highlightField.getFragments();
                String h_title = StringUtils.join(texts);
                map.put("h_title",h_title);
            }else {
                map.put("h_title",map.get("title"));
            }

            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
